package com.liuwei.msmall.search.controller;

import com.liuwei.msmall.common.dto.es.EsSkuModelDTO;
import com.liuwei.msmall.common.enums.BizeEnum;
import com.liuwei.msmall.common.utils.R;
import com.liuwei.msmall.search.service.ProductEsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

/**
 * @Classname ProductController
 * @Date 2021/4/10 2:56 下午
 * @Created by llww
 */
@RequestMapping("/es/product")
@RestController
@Slf4j
public class ProductController {

    @Resource
    ProductEsService productEsService;

    //保存商品到es中
    @PostMapping("/save")
    public R savePoduct(@RequestBody List<EsSkuModelDTO> esSkuModels){
        try {
            Boolean hasFailures = productEsService.saveToEs(esSkuModels);
            return hasFailures?R.error(BizeEnum.PRODUCT_UP_EXCEPTION.getCode()
                    ,BizeEnum.PRODUCT_UP_EXCEPTION.getMsg()):R.ok();
        } catch (IOException e) {
            log.error("上架商品信息失败 原因：{}",e.getMessage());
            return R.error(BizeEnum.PRODUCT_UP_EXCEPTION.getCode(),BizeEnum.PRODUCT_UP_EXCEPTION.getMsg());
        }

    }

    //根据spuid下架商品
    @GetMapping("/delete/{spuId}")
    public R deleteProduct(@PathVariable("spuId") Long spuId){
        try{
            productEsService.deleteFromEs(spuId);
            return R.ok();
        }catch (IOException e){
            log.error("下架商品失败 spuid{} e:{}",spuId,e);
            return R.error(BizeEnum.PRODUCT_DOWN_EXCEPTION);
        }

    }

}